﻿using System;
using Microsoft.SharePoint;

namespace GDExtensions
{
    /// <summary>
    /// Extension methods for the <see cref="T:Microsoft.SharePoint.SPGroup"/> class.
    /// </summary>
    /// <remarks></remarks>
    public static class SPGroupExtensions
    {
        #region Public Methods
        /// <summary>
        /// Method to clear the users in the group.
        /// </summary>
        /// <param name="group">The <see cref="T:Microsoft.SharePoint.SPGroup"/> group.</param>
        public static void Clear(this SPGroup group)
        {
            // Call the private method
            _Clear(group);
        }

        /// <summary>
        /// Method to see if the user is in the specified group.
        /// </summary>
        /// <param name="group">The <see cref="T:Microsoft.SharePoint.SPGroup"/> group.</param>
        /// <param name="user">The <see cref="T:Microsoft.SharePoint.SPUser"/> user.</param>
        /// <returns>True if the user is in the group, false otherwise.</returns>
        public static bool ContainsUser(this SPGroup group, SPUser user)
        {
            // Call the private method
            return _ContainsUser(group, user);
        }
        #endregion

        #region Private Methods
        /// <summary>
        /// Method to clear the users in the group.
        /// </summary>
        /// <param name="group">The <see cref="T:Microsoft.SharePoint.SPGroup"/> group.</param>
        private static void _Clear(SPGroup group)
        {
            // Ensure the group exists
            if (group == null) { return; }

            // Parse the users in the group
            foreach (SPUser user in group.Users)
            {
                // Remove the user
                group.RemoveUser(user);
            }

            // Update the group
            group.Update();
        }

        /// <summary>
        /// Method to see if the user is in the specified group.
        /// </summary>
        /// <param name="group">The <see cref="T:Microsoft.SharePoint.SPGroup"/> group.</param>
        /// <param name="user">The <see cref="T:Microsoft.SharePoint.SPUser"/> user.</param>
        /// <returns>True if the user is in the group, false otherwise.</returns>
        private static bool _ContainsUser(SPGroup group, SPUser user)
        {
            // Ensure the group exists
            if (group != null)
            {
                // Parse the users in the group
                foreach (SPUser groupUser in group.Users)
                {
                    // See if the user is in the group
                    if (groupUser.ID == user.ID) { return true; }
                }
            }

            // User was not found
            return false;
        }
        #endregion
    }
}
